package com.logjun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.logjun.reggie.common.BaseContext;
import com.logjun.reggie.common.CustomException;
import com.logjun.reggie.common.R;
import com.logjun.reggie.dto.OrdersDto;
import com.logjun.reggie.entity.*;
import com.logjun.reggie.service.AddressBookService;
import com.logjun.reggie.service.OrderDetailService;
import com.logjun.reggie.service.OrderService;
import com.logjun.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    AddressBookService addressBookService;

    /**
     * 订单提交
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    @CacheEvict(value = "orderCache",allEntries = true)
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("提交成功");
    }

    /**
     * 获取订单列表
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    @Cacheable(value = "orderCache",key = "'orderPage'+#page+'_'+#pageSize")
    public R<Page> page(int page, int pageSize){
        log.info(""+pageSize);
        pageSize = 5;
        Page<Orders> pageInfo = new Page(page,pageSize);
        //构造查询条件，按时间先后排序
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId()).orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, queryWrapper);
        //将pageInfo中的订单数据转换为OrdersDto对象，追加查询订单明细
        Page<OrdersDto> pageInfo1 = new Page();
        BeanUtils.copyProperties(pageInfo, pageInfo1, "records");
        List<OrdersDto> ordersDTOS = pageInfo.getRecords().stream().map(item ->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            //根据订单号查询
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> list = orderDetailService.list(queryWrapper1);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        pageInfo1.setRecords(ordersDTOS);
        return R.success(pageInfo1);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    @CacheEvict(value = "orderCache",allEntries = true)
    public R<String> payAgain(@RequestBody Orders orders){
        Long userId = BaseContext.getCurrentId();
        //根据订单号获得订单明细
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);
        //将订单明细中的菜品添加到购物车中
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            shoppingCart.setDishId(item.getDishId());
            if (null != item.getDishId()){

                shoppingCart.setDishId(item.getDishId());
            }else {
                shoppingCart.setSetmealId(item.getSetmealId());
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("添加购物车成功");
    }

    /**
     * 后台查询订单数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "orderCache",key = "'orderPage'+#page+'_'+#pageSize+'_'+#number+'_'" +
            "+#dateReserve.getBeginTime()+'_'+#dateReserve.getEndTime()")
    public R<Page> backendPage(int page, int pageSize, Long number, DateReserve dateReserve) {
        LocalDateTime beginTime = dateReserve.getBeginTime();
        LocalDateTime endTime = dateReserve.getEndTime();
        Page<Orders> pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //订单号模糊查询
        queryWrapper.like(null != number, Orders::getNumber, number);
        //订单日期模糊查询
        queryWrapper.ge(null != beginTime,Orders::getOrderTime,beginTime);
        queryWrapper.le(null != endTime,Orders::getOrderTime,endTime);
        //DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm-ss");
        //LocalDateTime begin = LocalDateTime.parse(beginTime, dateTimeFormatter);
        //LocalDateTime end = LocalDateTime.parse(endTime,dateTimeFormatter);
        //queryWrapper.like(null != beginTime,);
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        orderService.page(pageInfo,queryWrapper);
        Page<OrdersDto> pageInfo1 = new Page();
        BeanUtils.copyProperties(pageInfo,pageInfo1,"records");
        List<OrdersDto> ordersDTOS = pageInfo.getRecords().stream().map(item ->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            AddressBook addressBook = addressBookService.getById(item.getAddressBookId());
            if (addressBook == null){
                throw new CustomException("错误，地址不存在！");
            }
            ordersDto.setConsignee(addressBook.getConsignee());
            ordersDto.setAddress(addressBook.getDetail());
            return ordersDto;
        }).collect(Collectors.toList());
        pageInfo1.setRecords(ordersDTOS);
        return R.success(pageInfo1);
    }
 }
